package com.joe.pattern.factory.config_factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

/**
 * @Description
 * @Author 高建伟-joe
 * @Date 2023-12-28
 */
public class CoffeeFactory {

    //加载配置文件，获取配置文件中配置的全类名，并创建该类的对象进行存储
    //1.定义容器对象存储咖啡对象
    private static HashMap<String, Coffee> map = new HashMap<>(2);
    //2.加载配置文件，只需要加载一次
    static {
        //2.1 创建 properties 对象
        Properties properties = new Properties();
        //2.2 load 加载配置文件
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("application.yml");
        try {
            properties.load(is);
            Set<Object> keys = properties.keySet();
            for (Object key : keys) {
                String className = properties.getProperty((String) key);
                Class clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.newInstance();
                map.put((String) key, coffee);
            }
        }catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e){
            e.printStackTrace();
        }
    }

    // 根据名称获取对象
    public static Coffee createCoffee(String name){
        return map.get(name);
    }
}
